# -*- coding: UTF-8 -*-

from datetime import datetime
import sys
import decimal
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, DECIMAL, FLOAT
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger

__all__ = ['BillMonth']

class BillMonth(Base, SessionMixin):
    '''
    账单月度信息
    '''
    __tablename__ = "bill_month"
    bill_cycle = Column(String(64), nullable=False, comment='账期')
    cloud_platform = Column(String(64), nullable=True, comment='账单平台')
    pretax_amount = Column(DECIMAL(20,2), nullable=True, default=0, comment='应付金额')
    deducted_by_cash_coupons = Column(DECIMAL(10,2), default=0, nullable=True, comment='代金券抵扣')
    pay_amount = Column(DECIMAL(20,2), nullable=True, default=0, comment='实付金额')
    tax_amount = Column(DECIMAL(20,2), nullable=True, default=0, comment='税后金额')
    budget_amount = Column(DECIMAL(20,2), nullable=True, default=0, comment='预算金额')
    tax_budget = Column(DECIMAL(20,2), nullable=True, default=0, comment='税后预算')
    comment = Column(String(256), nullable=True, comment='月度信息')

    __table_args__ = (
        Index('idx_bill_analysis_bill_cycle_cloud_platform', 'bill_cycle', 'cloud_platform', unique=True),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic'
        }
    )

    def __repr__(self):
        return f"<month='{self.bill_cycle}', {self.pretax_amount}'>"


    def object_to_dict(self, db: Session):
        result ={}
        for key in self.__mapper__.c.keys():
            result[key] = getattr(self, key)
            if isinstance(result[key], decimal.Decimal):
                result[key] = float(result[key])
        return result


    @classmethod
    def get_object_by_bill_cycle(cls, db: Session, bill_cycle: str, cloud_platform: str):
        object = db.query(cls).filter(
            cls.bill_cycle == bill_cycle,
            cls.cloud_platform == cloud_platform
        ).first()
        return object


    @classmethod
    def get_object_info_by_cycle_platform(cls, db: Session, bill_cycle: str, cloud_platform: str):
        object = db.query(cls).filter(
            cls.bill_cycle == bill_cycle,
            cls.cloud_platform == cloud_platform
        ).to_dict_first()
        return object


    @classmethod
    def delete_cycle(cls, db: Session, bill_cycle: str):
        db.query(cls).filter(
            cls.bill_cycle == bill_cycle
        ).delete()
        db.commit()



    # 获取多个月份的月度账单
    @classmethod
    def get_months(cls, db: Session, months: list):
        try:
            data = db.query(cls).filter(
                cls.bill_cycle.in_(months)
            ).order_by(cls.bill_cycle).to_dict()
        except Exception as e:
            logger.exception(f'{sys._getframe().f_code.co_name} {e}')
            return None
        result = {
            "data": data,
            "fields": cls.get_display_field_meta()
        }

        return result




